package com.dys.hejiayuncommunity.web.controller.system;

import com.dys.hejiayuncommunity.common.constant.UserConstants;
import com.dys.hejiayuncommunity.common.core.controller.BaseController;
import com.dys.hejiayuncommunity.common.core.domain.BaseResponse;
import com.dys.hejiayuncommunity.common.core.domain.TreeSelect;
import com.dys.hejiayuncommunity.common.utils.SecurityUtils;
import com.dys.hejiayuncommunity.system.domain.SysDept;
import com.dys.hejiayuncommunity.system.service.SysDeptService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * @Author: 疾风
 * @ClassName: SysDeptController
 * @Description: 部门控制器
 * @CreateDate: 2024/12/06
 * @Version: v1.0.0
 */
@RestController
@RequestMapping(value = "/system/dept")
public class SysDeptController extends BaseController {

    @Autowired
    private SysDeptService sysDeptService;

    @PreAuthorize("@pe.hasPerms('system:dept:list')")
    @GetMapping(value = "/listDepartments")
    public BaseResponse<List<SysDept>> listDepartment(SysDept dept) {
        List<SysDept> list = sysDeptService.listDepartments(dept);
        return BaseResponse.success(list);
    }

    /**
     * 根据部门编号获取部门信息
     *
     * @param deptId 部门编号
     * @return 部门信息
     */
    @GetMapping(value = {"/{deptId}"})
    public BaseResponse getInfo(@PathVariable Long deptId) {
        return BaseResponse.success(sysDeptService.selectDeptById(deptId));
    }

    /**
     * 新增部门信息
     *
     * @param sysDept 部门信息
     * @return 响应结果
     */
    @PostMapping
    public BaseResponse add(@RequestBody SysDept sysDept) {
        if (UserConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(sysDept))) {
            return BaseResponse.failed("新增部门" + sysDept.getDeptName() + "失败,部门名称已经存在");
        }
        sysDept.setCreateBy(SecurityUtils.getUserName());
        return super.toAjax(sysDeptService.insertDept(sysDept));
    }

    /**
     * 修改部门信息
     *
     * @param dept 部门信息
     * @return 响应结果
     */
    @PutMapping
    public BaseResponse edit(@RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return BaseResponse.failed("修改部门" + dept.getDeptName() + "失败,部门名称已经存在");
        } else if (dept.getDeptId().equals(dept.getParentId())) {
            return BaseResponse.failed("修改部门" + dept.getDeptName() + "失败,上级部门不能是自己");
        }
        dept.setUpdateBy(SecurityUtils.getUserName());
        return super.toAjax(sysDeptService.updateDept(dept));
    }

    /**
     * 删除部门信息
     *
     * @param deptId 部门编号
     * @return 响应结果
     */
    @DeleteMapping(value = {"/{deptId}"})
    public BaseResponse remove(@PathVariable Long deptId) {
        if (sysDeptService.hasChildByDeptId(deptId)) {
            return BaseResponse.failed("存在下级部门,不允许删除");
        }

        if (sysDeptService.checkDeptExistUser(deptId)) {
            return BaseResponse.failed("部门存在用户,不允许删除");
        }
        return super.toAjax(sysDeptService.deleteDeptById(deptId));
    }

    @GetMapping(value = {"/treeselect"})
    public BaseResponse<List<TreeSelect>> treeSelect(SysDept sysDept){
        List<SysDept> list = sysDeptService.listDepartments(sysDept);
        return BaseResponse.success(sysDeptService.buildDeptTreeSelect(list));
    }

    /**
     * 查询部门列表(排除当前节点)
     */
    @GetMapping("/list/exclude/{deptId}")
    public BaseResponse excludeChild(@PathVariable(value = "deptId",required = false) Long deptId){
        List<SysDept> deptList = sysDeptService.listDepartments(new SysDept());
        Iterator<SysDept> iterator = deptList.iterator();
        while (iterator.hasNext()){
            SysDept nextDept = iterator.next();
            if(nextDept.getDeptId().intValue()==deptId ||
                    ArrayUtils.contains(StringUtils.split(nextDept.getAncestors(),","),deptId+"")){
                iterator.remove();
            }
        }
        return BaseResponse.success(deptList);
    }
}
